﻿using System;
using System.Drawing;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BCDataCenter.BOL;

public partial class WebMaster_Administrator_Users_Default : System.Web.UI.Page
{
    string error = "";
    DataTable dtList = new DataTable();
    ClassExecute.ClassExecute dt;
    string str = BCDataCenter.Configuration.CurrentConnectionString;
    static bool flag = false;
    protected void Page_Load(object sender, EventArgs e)
    {
              
        if (!IsPostBack)
        {
            LoadSiteCodeList();
          
        }
    }
    private void LoadSiteCodeList()
    {
        BWUser obj = new BWUser();
        try
        {            
            cbbTTPP.DataSource = obj.dsTTPPList(ref error);            
            cbbTTPP.DataTextField = "sitename";
            cbbTTPP.DataValueField = "Sitecode";            
            cbbTTPP.DataBind();
            
        }
        catch
        {
            //lbMessenge.Text = ex.ToString();
            return;
        }
    }
    private void LoadData()
    {
        BWUser obj = new BWUser();
        try
        {
            dtList = obj.dsList(ref error).Tables[0];
        }
        catch
        {
            return;
        }

    }
    private void NewMis()
    {
        txtUserName.ReadOnly = false;
        txtUserName.BackColor = Color.White;
        flag = true;
        txtUserName.Text = "";
        CheckBoxOneConnect.Checked = false;
        CheckBoxConnected.Checked = false;
        txtMatKhau.Text = "";
        txtXacNhanMK.Text = "";
        txtMieuTa.Text = "";
        DropDownListQuyenHan.SelectedIndex = 0;

    }
    protected void btnNew_Click(object sender, ImageClickEventArgs e)
    {
        NewMis();
    }
    
    static public string GetMd5Sum(string str)
    {
        // First we need to convert the string into bytes, which
        // means using a text encoder.

        Encoder enc = System.Text.Encoding.Unicode.GetEncoder();
        // Create a buffer large enough to hold the string

        byte[] unicodeText = new byte[str.Length * 2];

        enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

        // Now that we have a byte array we can ask the CSP to hash it

        MD5 md5 = new MD5CryptoServiceProvider();

        byte[] result = md5.ComputeHash(unicodeText);

        // Build the final string by converting each byte

        // into hex and appending it to a StringBuilder

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < result.Length; i++)
        {

            sb.Append(result[i].ToString("X2"));

        }
        // And return it
        return sb.ToString();
    }
    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        BWUser obj = new BWUser();
        string pass = GetMd5Sum(txtMatKhau.Text);
        
        if (flag)
            {

                if (obj.Insert(ref error, txtUserName.Text, txtMieuTa.Text,pass,txtMatKhau.Text, CheckBoxOneConnect.Checked, CheckBoxConnected.Checked, cbbTTPP.SelectedItem.Value, DropDownListQuyenHan.SelectedItem.Value,true))
                {
                   
                    uscMsgBox1.AddMessage("Lưu thông tin thành công.", uscMsgBox.enmMessageType.Success);
                    txtUserName.ReadOnly = true;
                    txtUserName.BackColor = Color.Yellow;
                }
                else
                {
                    uscMsgBox1.AddMessage("Lưu thông tin thất bại.\n" + error, uscMsgBox.enmMessageType.Error);
                }
                flag = false;
            }
            else
            {
                if (obj.Update(ref error, txtUserName.Text, txtMieuTa.Text,pass,txtMatKhau.Text, CheckBoxOneConnect.Checked, CheckBoxConnected.Checked, cbbTTPP.SelectedItem.Value, DropDownListQuyenHan.SelectedItem.Value,CheckBoxConnected.Checked))
                {
                   
                    uscMsgBox1.AddMessage("Cập nhật thông tin thành công.",uscMsgBox.enmMessageType.Success);
                }
                else
                {
                    uscMsgBox1.AddMessage("Cập nhật thông tin thất bại.\n" + error, uscMsgBox.enmMessageType.Error);
                }
            }
        
    }
   
    protected void btnFind_Click(object sender, ImageClickEventArgs e)
    {
        TabContainer1.ActiveTabIndex = 1;
    }
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "K_FindUserSystem", CommandType.StoredProcedure,
            new SqlParameter("@parameter", txtSearch.Text));
        if (db.Rows.Count == 1)
        {
            GetUser(db.Rows[0]["UserName"].ToString());
            TabContainer1.ActiveTabIndex = 0;
            txtUserName.ReadOnly = true;
            txtUserName.BackColor = Color.Yellow;
            flag = false;

        }
        else
        {
            GridView2.DataSource = db;
            GridView2.DataBind();
        }
    }
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "K_FindUserSystem", CommandType.StoredProcedure,
            new SqlParameter("@parameter", txtSearch.Text));
        if (db.Rows.Count == 1)
        {
            GetUser(db.Rows[0]["UserName"].ToString());
            TabContainer1.ActiveTabIndex = 0;
        }
        else
        {
            GridView2.DataSource = db;
            GridView2.DataBind();
        }
    }
    void GetUser(string UserName)
    {
         dt = new ClassExecute.ClassExecute();
         DataTable db = dt.Get_Data_DataTable(str, ref error, "K_GetUser", CommandType.StoredProcedure,
            new SqlParameter("@UserName", UserName));
         if (db.Rows.Count != 0)
         {
             txtUserName.Text = db.Rows[0]["UserName"].ToString();

             txtMatKhau.Text = db.Rows[0]["PassHint"].ToString();
             txtMatKhau.Attributes.Add("value", db.Rows[0]["PassHint"].ToString());

             txtXacNhanMK.Text = db.Rows[0]["PassHint"].ToString();
             txtXacNhanMK.Attributes.Add("value", db.Rows[0]["PassHint"].ToString());

             txtMieuTa.Text = db.Rows[0]["UserDescription"].ToString();
              try
             {
                 DropDownListQuyenHan.SelectedValue = db.Rows[0]["UserType"].ToString();
             }
             catch
             {
                 DropDownListQuyenHan.SelectedIndex = -1;
             }
              try
             {
                 cbbTTPP.SelectedValue = db.Rows[0]["Sitecode"].ToString();
             }
             catch
             {
                 cbbTTPP.SelectedIndex = -1;
             }

              CheckBoxOneConnect.Checked = bool.Parse(db.Rows[0]["OneConection"].ToString());
              CheckBoxConnected.Checked = bool.Parse(db.Rows[0]["Conected"].ToString());
             
              txtUserName.Enabled = false;
             
         }
        
    }
    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
         GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
         if (e.CommandName == "chon")
         {
             GetUser(grv.Cells[0].Text);
             TabContainer1.ActiveTabIndex = 0;
             txtUserName.ReadOnly = true;
             txtUserName.BackColor = Color.Yellow;
             flag = false;
         }
    }
    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView2.PageIndex = e.NewPageIndex;
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "K_FindUserSystem", CommandType.StoredProcedure,
            new SqlParameter("@parameter", txtSearch.Text));
        GridView2.DataSource = db;
        GridView2.DataBind();
    }
}
